import { Entity, Column, PrimaryGeneratedColumn, ManyToOne, JoinColumn, PrimaryColumn, OneToMany, CreateDateColumn, BeforeInsert } from "typeorm";

@Entity()
export class Chat {
  @OneToMany(() => ChatMeta, (meta: ChatMeta) => meta.chat_id)
  @PrimaryGeneratedColumn()
  public readonly id: number;

  @Column({unique: true})
  code: string;

  @CreateDateColumn()
  time: Date;

  @Column({ type: 'varchar', length: 60, nullable: false})
  title: string;

  @Column({ type: 'text', default: ''})
  deltail: string;

  @Column({ default:0 })
  tokens: number;

  @Column({ default:0 })
  message: number;

  @Column()
  model: string;
  
  @BeforeInsert() //实体的装饰器方法，用于在保存实体之前生成并设置代码编码。
  generateCode() {
    const currentDate = new Date();
    const datePart = currentDate.toISOString().slice(0, 10).replace(/-/g, '');
    const randomPart = Math.random().toString(36).slice(2, 8).toUpperCase();
    this.code = `${datePart}-${randomPart}`;
  }
}

@Entity()
export class ChatMeta{
  @PrimaryGeneratedColumn()
  public readonly id: number;

  @ManyToOne(() => Chat, (chat: Chat) => chat.id)
  @JoinColumn({ name: 'chat_id' })
  public readonly chat_id: number;

  @Column({ type: 'varchar', length: 60, unique: true })
  public readonly meta_key: string;

  @Column({ type: 'text', default: ''})
  meta_value: string;
}